var log = console.log.bind(console)
var loadLevels = function (n) {
    n = n - 1
    var blocks = []
    var level = levels[n]
    for (var i = 0; i < level.length; i++) {
        var p = level[i];
        var b = Blcok(p)
        // set block                 
        blocks.push(b)
    }

    return blocks
}

var blocks = []
var enableDebugMode = function(enable)
{
    if(!enable)
    {
        return
    }

    window.paused = true
    window.addEventListener('keydown', function(event){
        var key = event.key
        if(key == 'p')
        {
            window.paused = !window.paused
        }
        else if('123456'.includes(key))
        {
            blocks = loadLevels(key)
        }
        
    })

    // range
    document.querySelector('#id-input-speed').addEventListener('input', function () {
        var input = event.target
        //log(event, input.value)
        window.fps = Number(input.value)
        log(window.fps)
    })
}


var _main = function(){
    log('_main')

    paused = true
        // 为了debug临时加的
    enableDebugMode(true)

    var images = {
        ball: 'ball.png',
        block: 'block.png',
        paddle: 'paddle.png',
        }
        var game = GuaGame(30, images)
    var paddle = Paddle(game)
    var ball = Ball(game)
    
    var score = 0
    blocks = loadLevels(1)

    game.registerAction('a', function(){
        paddle.moveLeft()
    })
    game.registerAction('d', function(){
        paddle.moveRight()
    })

    game.registerAction('f', function(){
        ball.fire()
    })



    game.update = function () { 
        if(!window.paused)
        {
            return
        }
        ball.move()  

        //判断相撞
        if (paddle.collide(ball)) {
            ball.reverse()                    
        }    
        // 判断ball和blocks相撞
        for (var i = 0; i < blocks.length; i++) {
            var block = blocks[i]
            if (block.collide(ball)) {
                log("判断ball和block相撞")
                block.kill()
                ball.reverse()

                //更新分数
                score += 10
            } 
        }
                
    }
    game.draw = function (){
        //draw
        //game.context.drawImage(paddle.image, paddle.x, paddle.y)
        game.drawImage(paddle) 
        game.drawImage(ball)

        for (var i = 0; i < blocks.length; i++) {
            var block = blocks[i]
            if (block.alive) {
                game.drawImage(block)
            }
        }     
        
        // draw lables
        game.context.fillText('分数：'+ score, 10, 290)
    }
    }
_main()